大家好~
今天來認識如何自定義錯誤訊息且不用另外建立 FormRequest class 的方式吧~
Validator::make() 可以接受四個參數,
依序是:

$rules=[
    'title' => 'required|string|max:50',
    'content' => 'required|string|between:2,255'
];
$messages = [
    'required' => ':attribute 未填。',
    'string' => ':attribute 格式不支援。',
    'between' => ':attribute 文字長度請在:min至:max間。',
    'title.max' => ':attribute 文字長度請在:max以內。',
];
Validator::make($request->all(), $rules, $messages)->validate();
將我們定義好的參數依序放入即可~
以 Day05 我們完成的新增留言功能為例,
完整程式看起來會像這樣:
public function store(Request $request)
{
    $rules=[
        'title' => 'required|string|max:50',
        'content' => 'required|string|between:2,255'
    ];
    $messages = [
        'required' => ':attribute 未填。',
        'string' => ':attribute 格式不支援。',
        'between' => ':attribute 文字長度請在:min至:max間。',
        'title.max' => ':attribute 文字長度請在:max以內。',
    ];
    $validated = Validator::make($request->all(), $rules, $messages)->validate();
    $message = Auth::user()->messages()->create($validated);
    return response(MessageResource::make($message), Response::HTTP_CREATED);
}
然後來測試看看吧~
下圖就是剛剛我們自定義的錯誤訊息喔!
 
Validator::make()。那麼關於 Validation 的部分差不多就這樣啦~
今天差不多先這樣啦!
大家明天見啦~
若文章有任何問題,
還請大家不吝賜教!